  

package c.x.jy.wexin.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import c.x.jy.common.annotation.Device;
import c.x.jy.common.annotation.Login;
import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.CookieUtil;
import c.x.jy.dao.entity.BusinessEntity;
import c.x.jy.dao.entity.MemberEntity;
import c.x.jy.service.config.WechatConfigService;
import c.x.jy.service.entity.form.CommRequest;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.service.BusinessService;
import c.x.jy.service.service.MemberService;
import c.x.jy.service.utils.MemberUtil;
import c.x.jy.service.utils.wechat.WechatConfig;
import c.x.jy.service.utils.wechat.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限(Token)验证
 *
 */ 
@Slf4j
@Component
public class  AuthorizationInterceptor extends org.springframework.web.servlet.handler.HandlerInterceptorAdapter {
 
	   @Autowired 
	   private MemberService memberService;
	   
	   @Autowired
	 	private BusinessService businessService;
		@Autowired
		private Cache redisUtils;
	   @Autowired
	    private  WechatConfigService wechatConfigService;
	  
	 

    public static final String USER_KEY = "token";
    public static final String BUSINESS_KEY = "bcode";
    public static final String referralCode_KEY = "mcode";

 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //System.out.println(request.getRequestURL().toString() + "?" +  request.getQueryString());
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
           // System.out.println(" no Token..."+request.getRequestURI());
            return true;
        }

        if(annotation == null){
            return true;
        }
 
    
        MemberEntity  member=  null; 
   
        CommRequest  cust=null;
        //获取用户凭证
        String openid = request.getHeader(USER_KEY);
 
    
        String businessCode = request.getHeader(BUSINESS_KEY);
        String referralCode = request.getHeader(referralCode_KEY);
        if(StringUtils.isEmpty(openid) ){
            openid = request.getParameter(USER_KEY);
        }
        if(StringUtils.isEmpty(openid) ){
        	 openid = CookieUtil.getCookieValue(request, USER_KEY, false);
        }
        if(StringUtils.isEmpty(referralCode) ){
            referralCode = CookieUtil.getCookieValue(request, referralCode_KEY, false);
        }
        if(StringUtils.isEmpty(referralCode) ){
            referralCode = request.getParameter(referralCode_KEY);
        }
  
        if(StringUtils.isEmpty(businessCode) ){
            businessCode = request.getParameter(BUSINESS_KEY);
        }
        if(!StringUtils.isEmpty(openid)) {
        	    cust=       (CommRequest) redisUtils.get(openid, CommRequest.class);
        } 
     
        if((StringUtils.isEmpty(businessCode)||businessCode.equals("null")||businessCode.equals("undefined"))&&cust!=null) {
            businessCode=cust.getBusinessCode();
        }
        if((StringUtils.isEmpty(referralCode)||referralCode.equals("null")||referralCode.equals("undefined"))&&cust!=null) {
            referralCode=cust.getMcode();
        }
        if(  StringUtils.isEmpty(businessCode)){
            throw new RRException(  "代理Code不能为空！", 2);
        }
        log.info("businessCode:"+businessCode);
        BusinessEntity b = businessService.selectBusinessByCode(businessCode);
        if(  b==null||!b.getStatus().equals(1)){
            throw new RRException(  "代理Code有误！", 2);
        }
   
    	//CookieUtil.doSetCookie(request, httpResponse, "token", token, EXPIRE*10, true);
       
        log.info("openid:"+ openid);
        if(!StringUtils.isEmpty( openid) ) {
            member=      memberService.getMemberByOpenId(openid);
            redisUtils.set(openid, new CommRequest(openid,businessCode,referralCode), 50*60l);
        }
        MemberUtil.set(new CommRequest(openid,businessCode,referralCode));

       if(member==null) {
           WechatConfig config= wechatConfigService.getDefultConfing();
    	  member=    WechatUtil.getUserByCode(request, response, config);
    	  if(member==null)return false;
    		//CookieUtil.doSetCookie(request, response, "token", member.getOpenid(), 60*10, true);


    		  member.setBusinessId(b.getId());
    	  memberService.saveOrUpdateByOpenid(member);
       }
       CookieUtil.doSetCookie(request, response, "token", member.getOpenid(), 60*50, true);
        CookieUtil.doSetCookie(request, response, "bcode", businessCode, 60*50, true);

        MemberUtil.set(new CommRequest(member.getOpenid(),businessCode,referralCode));
        redisUtils.set(member.getOpenid(), new CommRequest(member.getOpenid(),businessCode,referralCode), 50*60l);
        return true;
    }
    
 
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		//System.out.println("remove Token..."+request.getRequestURI());
		MemberUtil.remove();
	}
}
